import json

from api.vm.apis import VmApi
from testcases.bundle.patch_distribution import PatchDistribution
from utils.log import log
from fastapi import APIRouter, Request, BackgroundTasks
from fastapi.responses import JSONResponse,HTMLResponse,Response

cginstance_agent = APIRouter()


@cginstance_agent.post("/find_source_group_version/ip/{ip}")
async def find_source_group_version(request: Request,ip):
    response = None
    try:
        raw_body = await request.body()
        request_str = raw_body.decode("utf-8")
        log.info(f"request_str={request_str}")  # 将字节转换为字符串
        request_json = json.loads(request_str)
    except:
        request_json = None
    try:
        resp = VmApi(ip).tail_log()
        resp_json = {
            "ret": {
                "code": 200,
                "reason": "",
                "msg": resp,
            }
        }
        response = JSONResponse(content=resp_json, status_code=200, media_type='application/json')
    except:
        resp_json = {
            "ret": {
                "code": 500,
                "reason": "",
                "msg": "分发异常",
            }
        }
        response = JSONResponse(content=resp_json, status_code=200, media_type='application/json')

    log.error(f"response={resp_json}")
    return response